#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <poll.h>

//简单的poll多路转接TCP客户端
//poll默认支持LT模式,使用非阻塞读

void SetNonBlock(int fd)
{
    int flags = fcntl(fd,F_GETFL,0);//显示传0表示无额外参数
    fcntl(fd,F_SETFL,flags | O_NONBLOCK);//设置非阻塞
}

int BulidConnect(int listensock)
{
    int sockfd = accept(listensock,nullptr,nullptr);//不关心客户端情况
    return sockfd;
}

bool ReadMessage(int sockfd)
{
    //非阻塞模式下,循环读取,以读取完所有内容
    std::string str;
    while(true)
    {
        char buffer[1024] = {0};
        int n = recv(sockfd,buffer,sizeof(buffer) - 1,0); 
        // std::cout << "读取到的数据大小是:" << n << std::endl;
        if(n <= sizeof(buffer) - 1 && n > 0)
        {
            //不确定数据是否读完,继续读
            buffer[n] = 0;
            str += buffer;
            continue;
        }
        else if(n == 0)
        {
            //对端连接关闭,同时接收缓冲区中也没有数据
            if(str.size())
            {
                std::cout << str << std::endl;
                std::string echo_str = "echo: " + str;
                send(sockfd,echo_str.c_str(),echo_str.size(),0);
            }
            close(sockfd);
            return false;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                //非阻塞模式下,数据读取完毕
                break;
            }
            else if(errno == EINTR)
                continue;
            else
                break;
        }
    }
    if(str.size())
    {
        std::cout << str << std::endl;
        std::string echo_str = "echo: " + str;
        send(sockfd,echo_str.c_str(),echo_str.size(),0);
    }
    return true;
}

int main()
{
    int listensock = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;//服务器显示绑定地址:任意IP绑定
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    if(bind(listensock,(struct sockaddr*)&addr,sizeof(addr)) != 0)
        std::cout << "bind error" << std::endl;
    if(listen(listensock,64) != 0)
        std::cout << "listen error" << std::endl;
    SetNonBlock(listensock);

    std::vector<struct pollfd> fd_queue;
    struct pollfd listen_poll;
    listen_poll.fd = listensock,listen_poll.events = POLLIN;//revents内核处理
    fd_queue.push_back(listen_poll);
    while(true)
    {
        std::vector<int> fd_add;//存储新增的sockfd
        std::vector<int> fd_del;//存储要删去的对应文件描述在fd_queue中的下标
        int n = poll(&fd_queue[0],fd_queue.size(),-1);//阻塞式
        if(n > 0)
        {
            for(int i = 0;i < fd_queue.size();i++)
            {
                int fd = fd_queue[i].fd;
                int events = fd_queue[i].revents;
                if(fd == listensock && (events & POLLIN))
                {
                    int sockfd = BulidConnect(fd);
                    SetNonBlock(sockfd);
                    fd_add.push_back(sockfd);
                }
                else if(events & POLLIN)
                {
                    if(!ReadMessage(fd))
                    {
                        std::cout << "对端连接关闭,要删除的文件描述符是: " << fd << std::endl;
                        fd_del.push_back(i);
                    }
                }                
            }
        }
        else if(n == 0)
        {
            std::cout << "timeout" << std::endl;
        }
        else
        {
            std::cout << "poll error" << std::endl;
            break;
        }
        
        //处理新增和删除
        //先处理删除,后处理新增,对于顺序表更优
        for(auto& pos : fd_del)
            fd_queue.erase(fd_queue.begin() + pos);
        for(auto& e : fd_add)
        {
            struct pollfd sock_poll;
            sock_poll.fd = e,sock_poll.events = POLLIN;
            fd_queue.push_back(sock_poll);
        }
    }
    return 0;
}